<template>
  <div class="space-y-6">
    <!-- 页面标题和操作 -->
    <div class="flex items-center justify-between">
      <div>
        <h1 class="text-2xl font-bold text-gray-900">费用管理</h1>
        <p class="text-gray-600 mt-1">管理车辆相关费用和成本分析</p>
      </div>
      <div class="flex space-x-2">
        <el-button type="success" :icon="Download" @click="exportData">
          导出报表
        </el-button>
        <el-button type="primary" :icon="Plus" @click="showAddDialog = true">
          添加费用
        </el-button>
      </div>
    </div>
    
    <!-- 费用统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
      <el-card class="stat-card">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-gray-600 text-sm">本月总费用</p>
            <p class="text-2xl font-bold text-red-600">¥{{ formatCurrency(monthlyStats.total) }}</p>
            <p class="text-xs text-gray-500 mt-1">
              <span :class="monthlyStats.totalChange >= 0 ? 'text-red-500' : 'text-green-500'">
                {{ monthlyStats.totalChange >= 0 ? '+' : '' }}{{ monthlyStats.totalChange }}%
              </span>
              较上月
            </p>
          </div>
          <el-icon class="text-3xl text-red-500"><Money /></el-icon>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-gray-600 text-sm">燃油费用</p>
            <p class="text-2xl font-bold text-orange-600">¥{{ formatCurrency(monthlyStats.fuel) }}</p>
            <p class="text-xs text-gray-500 mt-1">
              占总费用 {{ ((monthlyStats.fuel / monthlyStats.total) * 100).toFixed(1) }}%
            </p>
          </div>
          <el-icon class="text-3xl text-orange-500"><Odometer /></el-icon>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-gray-600 text-sm">维修费用</p>
            <p class="text-2xl font-bold text-blue-600">¥{{ formatCurrency(monthlyStats.maintenance) }}</p>
            <p class="text-xs text-gray-500 mt-1">
              占总费用 {{ ((monthlyStats.maintenance / monthlyStats.total) * 100).toFixed(1) }}%
            </p>
          </div>
          <el-icon class="text-3xl text-blue-500"><Tools /></el-icon>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-gray-600 text-sm">其他费用</p>
            <p class="text-2xl font-bold text-purple-600">¥{{ formatCurrency(monthlyStats.other) }}</p>
            <p class="text-xs text-gray-500 mt-1">
              占总费用 {{ ((monthlyStats.other / monthlyStats.total) * 100).toFixed(1) }}%
            </p>
          </div>
          <el-icon class="text-3xl text-purple-500"><More /></el-icon>
        </div>
      </el-card>
    </div>
    
    <!-- 费用趋势图表 -->
    <el-card>
      <template #header>
        <div class="flex items-center justify-between">
          <span class="font-medium">费用趋势分析</span>
          <el-radio-group v-model="chartPeriod" size="small">
            <el-radio-button label="week">近7天</el-radio-button>
            <el-radio-button label="month">近30天</el-radio-button>
            <el-radio-button label="quarter">近3个月</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <div class="h-80 flex items-center justify-center bg-gray-50 rounded">
        <div class="text-center text-gray-500">
          <el-icon class="text-4xl mb-2"><TrendCharts /></el-icon>
          <p>费用趋势图表</p>
          <p class="text-sm">（此处可集成 ECharts 或其他图表库）</p>
        </div>
      </div>
    </el-card>
    
    <!-- 搜索和筛选 -->
    <el-card>
      <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
        <el-input
          v-model="searchQuery"
          placeholder="搜索车牌号或费用描述"
          :prefix-icon="Search"
          clearable
        />
        <el-select v-model="typeFilter" placeholder="费用类型" clearable>
          <el-option label="燃油费" value="fuel" />
          <el-option label="维修费" value="maintenance" />
          <el-option label="保险费" value="insurance" />
          <el-option label="停车费" value="parking" />
          <el-option label="过路费" value="toll" />
          <el-option label="其他" value="other" />
        </el-select>
        <el-select v-model="vehicleFilter" placeholder="选择车辆" clearable>
          <el-option label="京A12345" value="京A12345" />
          <el-option label="京B67890" value="京B67890" />
          <el-option label="京C11111" value="京C11111" />
        </el-select>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
        <el-button @click="resetFilters">重置筛选</el-button>
      </div>
    </el-card>
    
    <!-- 费用记录列表 -->
    <el-card>
      <template #header>
        <div class="flex items-center justify-between">
          <span class="font-medium">费用记录</span>
          <div class="text-sm text-gray-500">
            共 {{ filteredExpenses.length }} 条记录，总金额 ¥{{ formatCurrency(totalFilteredAmount) }}
          </div>
        </div>
      </template>
      
      <el-table :data="paginatedExpenses" stripe style="width: 100%">
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="date" label="日期" width="120" sortable />
        <el-table-column prop="vehiclePlate" label="车牌号" width="100" />
        <el-table-column label="费用类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.type)" size="small">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="费用描述" min-width="150" />
        <el-table-column prop="amount" label="金额(元)" width="120" sortable>
          <template #default="{ row }">
            <span class="font-medium text-red-600">¥{{ formatCurrency(row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100" />
        <el-table-column prop="operator" label="操作人" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 'approved' ? 'success' : row.status === 'pending' ? 'warning' : 'danger'"
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewExpense(row)">查看</el-button>
            <el-button size="small" type="primary" @click="editExpense(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteExpense(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="flex justify-center mt-6">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredExpenses.length"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑费用对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingExpense ? '编辑费用' : '添加费用'"
      width="600px"
    >
      <el-form
        ref="expenseFormRef"
        :model="expenseForm"
        :rules="expenseRules"
        label-width="100px"
      >
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <el-form-item label="日期" prop="date">
            <el-date-picker
              v-model="expenseForm.date"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              class="w-full"
            />
          </el-form-item>
          <el-form-item label="车牌号" prop="vehiclePlate">
            <el-select v-model="expenseForm.vehiclePlate" placeholder="选择车辆" class="w-full">
              <el-option label="京A12345" value="京A12345" />
              <el-option label="京B67890" value="京B67890" />
              <el-option label="京C11111" value="京C11111" />
            </el-select>
          </el-form-item>
          <el-form-item label="费用类型" prop="type">
            <el-select v-model="expenseForm.type" placeholder="选择类型" class="w-full">
              <el-option label="燃油费" value="fuel" />
              <el-option label="维修费" value="maintenance" />
              <el-option label="保险费" value="insurance" />
              <el-option label="停车费" value="parking" />
              <el-option label="过路费" value="toll" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
          <el-form-item label="金额" prop="amount">
            <el-input-number
              v-model="expenseForm.amount"
              :min="0"
              :precision="2"
              placeholder="请输入金额"
              class="w-full"
            />
          </el-form-item>
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="expenseForm.paymentMethod" placeholder="选择支付方式" class="w-full">
              <el-option label="现金" value="cash" />
              <el-option label="银行卡" value="card" />
              <el-option label="支付宝" value="alipay" />
              <el-option label="微信" value="wechat" />
              <el-option label="公司账户" value="company" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="expenseForm.status" placeholder="选择状态" class="w-full">
              <el-option label="待审核" value="pending" />
              <el-option label="已审核" value="approved" />
              <el-option label="已拒绝" value="rejected" />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="费用描述" prop="description">
          <el-input
            v-model="expenseForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入费用描述"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="expenseForm.notes"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="saveExpense">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 费用详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="费用详情" width="600px">
      <div v-if="selectedExpense" class="space-y-4">
        <div class="grid grid-cols-2 gap-4">
          <div class="bg-gray-50 p-4 rounded-lg">
            <h3 class="font-medium text-gray-900 mb-2">基本信息</h3>
            <div class="space-y-2 text-sm">
              <div class="flex justify-between">
                <span class="text-gray-600">编号:</span>
                <span class="font-medium">{{ selectedExpense.id }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">日期:</span>
                <span class="font-medium">{{ selectedExpense.date }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">车牌号:</span>
                <span class="font-medium">{{ selectedExpense.vehiclePlate }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">类型:</span>
                <el-tag :type="getTypeColor(selectedExpense.type)" size="small">
                  {{ getTypeText(selectedExpense.type) }}
                </el-tag>
              </div>
            </div>
          </div>
          <div class="bg-gray-50 p-4 rounded-lg">
            <h3 class="font-medium text-gray-900 mb-2">费用信息</h3>
            <div class="space-y-2 text-sm">
              <div class="flex justify-between">
                <span class="text-gray-600">金额:</span>
                <span class="font-medium text-red-600 text-lg">¥{{ formatCurrency(selectedExpense.amount) }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">支付方式:</span>
                <span class="font-medium">{{ selectedExpense.paymentMethod }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">操作人:</span>
                <span class="font-medium">{{ selectedExpense.operator }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">状态:</span>
                <el-tag
                  :type="selectedExpense.status === 'approved' ? 'success' : selectedExpense.status === 'pending' ? 'warning' : 'danger'"
                  size="small"
                >
                  {{ getStatusText(selectedExpense.status) }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
        <div class="bg-gray-50 p-4 rounded-lg">
          <h3 class="font-medium text-gray-900 mb-2">费用描述</h3>
          <p class="text-gray-700">{{ selectedExpense.description }}</p>
        </div>
        <div v-if="selectedExpense.notes" class="bg-gray-50 p-4 rounded-lg">
          <h3 class="font-medium text-gray-900 mb-2">备注</h3>
          <p class="text-gray-700">{{ selectedExpense.notes }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Download, Money, Odometer, Tools, More, TrendCharts } from '@element-plus/icons-vue'

// 接口定义
interface Expense {
  id: number
  date: string
  vehiclePlate: string
  type: 'fuel' | 'maintenance' | 'insurance' | 'parking' | 'toll' | 'other'
  description: string
  amount: number
  paymentMethod: string
  operator: string
  status: 'pending' | 'approved' | 'rejected'
  notes?: string
}

interface MonthlyStats {
  total: number
  fuel: number
  maintenance: number
  other: number
  totalChange: number
}

// 响应式数据
const showAddDialog = ref(false)
const showDetailDialog = ref(false)
const editingExpense = ref<Expense | null>(null)
const selectedExpense = ref<Expense | null>(null)
const searchQuery = ref('')
const typeFilter = ref('')
const vehicleFilter = ref('')
const dateRange = ref<[string, string] | null>(null)
const currentPage = ref(1)
const pageSize = ref(10)
const chartPeriod = ref('month')

// 费用表单
const expenseForm = reactive({
  date: '',
  vehiclePlate: '',
  type: '' as Expense['type'],
  description: '',
  amount: 0,
  paymentMethod: '',
  status: 'pending' as Expense['status'],
  notes: ''
})

// 表单验证规则
const expenseRules = {
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  vehiclePlate: [{ required: true, message: '请选择车辆', trigger: 'change' }],
  type: [{ required: true, message: '请选择费用类型', trigger: 'change' }],
  description: [{ required: true, message: '请输入费用描述', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
  paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 月度统计数据
const monthlyStats = ref<MonthlyStats>({
  total: 45680,
  fuel: 28500,
  maintenance: 12800,
  other: 4380,
  totalChange: 8.5
})

// 模拟费用数据
const expenses = ref<Expense[]>([
  {
    id: 1,
    date: '2024-01-15',
    vehiclePlate: '京A12345',
    type: 'fuel',
    description: '加油费用 - 中石化加油站',
    amount: 350.00,
    paymentMethod: '公司账户',
    operator: '王师傅',
    status: 'approved'
  },
  {
    id: 2,
    date: '2024-01-14',
    vehiclePlate: '京B67890',
    type: 'maintenance',
    description: '更换机油和机滤',
    amount: 480.00,
    paymentMethod: '银行卡',
    operator: '李师傅',
    status: 'approved'
  },
  {
    id: 3,
    date: '2024-01-13',
    vehiclePlate: '京A12345',
    type: 'parking',
    description: '停车费 - 商务中心',
    amount: 25.00,
    paymentMethod: '现金',
    operator: '张师傅',
    status: 'pending'
  },
  {
    id: 4,
    date: '2024-01-12',
    vehiclePlate: '京C11111',
    type: 'toll',
    description: '高速过路费 - 京沪高速',
    amount: 85.00,
    paymentMethod: '微信',
    operator: '赵师傅',
    status: 'approved'
  },
  {
    id: 5,
    date: '2024-01-11',
    vehiclePlate: '京B67890',
    type: 'insurance',
    description: '车辆保险费用',
    amount: 2800.00,
    paymentMethod: '公司账户',
    operator: '管理员',
    status: 'approved'
  }
])

// 计算属性
const filteredExpenses = computed(() => {
  let filtered = expenses.value
  
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(expense => 
      expense.vehiclePlate.toLowerCase().includes(query) ||
      expense.description.toLowerCase().includes(query)
    )
  }
  
  if (typeFilter.value) {
    filtered = filtered.filter(expense => expense.type === typeFilter.value)
  }
  
  if (vehicleFilter.value) {
    filtered = filtered.filter(expense => expense.vehiclePlate === vehicleFilter.value)
  }
  
  if (dateRange.value && dateRange.value.length === 2) {
    const [start, end] = dateRange.value
    filtered = filtered.filter(expense => 
      expense.date >= start && expense.date <= end
    )
  }
  
  return filtered.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
})

const paginatedExpenses = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredExpenses.value.slice(start, end)
})

const totalFilteredAmount = computed(() => {
  return filteredExpenses.value.reduce((sum, expense) => sum + expense.amount, 0)
})

// 方法
const formatCurrency = (amount: number) => {
  return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

const getTypeColor = (type: Expense['type']) => {
  const colors = {
    fuel: 'warning',
    maintenance: 'primary',
    insurance: 'success',
    parking: 'info',
    toll: 'warning',
    other: 'default'
  }
  return colors[type]
}

const getTypeText = (type: Expense['type']) => {
  const texts = {
    fuel: '燃油费',
    maintenance: '维修费',
    insurance: '保险费',
    parking: '停车费',
    toll: '过路费',
    other: '其他'
  }
  return texts[type]
}

const getStatusText = (status: Expense['status']) => {
  const texts = {
    pending: '待审核',
    approved: '已审核',
    rejected: '已拒绝'
  }
  return texts[status]
}

const resetFilters = () => {
  searchQuery.value = ''
  typeFilter.value = ''
  vehicleFilter.value = ''
  dateRange.value = null
  ElMessage.success('筛选条件已重置')
}

const viewExpense = (expense: Expense) => {
  selectedExpense.value = expense
  showDetailDialog.value = true
}

const editExpense = (expense: Expense) => {
  editingExpense.value = expense
  Object.assign(expenseForm, expense)
  showAddDialog.value = true
}

const deleteExpense = (expense: Expense) => {
  ElMessageBox.confirm(
    `确定要删除这条费用记录吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = expenses.value.findIndex(e => e.id === expense.id)
    if (index > -1) {
      expenses.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  })
}

const saveExpense = () => {
  if (editingExpense.value) {
    // 编辑现有费用
    const index = expenses.value.findIndex(e => e.id === editingExpense.value!.id)
    if (index > -1) {
      expenses.value[index] = { ...editingExpense.value, ...expenseForm }
      ElMessage.success('费用记录更新成功')
    }
  } else {
    // 添加新费用
    const newExpense: Expense = {
      id: Date.now(),
      ...expenseForm,
      operator: '当前用户' // 实际应用中从用户状态获取
    }
    expenses.value.push(newExpense)
    ElMessage.success('费用记录添加成功')
  }
  
  cancelEdit()
}

const cancelEdit = () => {
  showAddDialog.value = false
  editingExpense.value = null
  Object.assign(expenseForm, {
    date: '',
    vehiclePlate: '',
    type: '',
    description: '',
    amount: 0,
    paymentMethod: '',
    status: 'pending',
    notes: ''
  })
}

const exportData = () => {
  ElMessage.success('费用报表导出功能开发中...')
}

// 组件挂载时加载数据
onMounted(() => {
  // 这里可以调用API加载实际数据
})
</script>

<style scoped>
.stat-card {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.el-card {
  border-radius: 8px;
}

.el-table {
  border-radius: 8px;
}
</style>